package net.zoneland.zoneapp.common.tree;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

/**
 * 树形ListView适配器 基础类
 * 
 * @author FancyLou
 * @date 2015年4月21日 下午10:54:44
 *
 * @param <T>
 */
public abstract class TreeListViewAdapter<T> extends BaseAdapter {

	@SuppressWarnings("unused")
	private Context context;
	private ListView tree;

	protected List<Node> allNodes;// 所有节点
	protected List<Node> visibleNodes;// 显示的node
	protected LayoutInflater inflater;

	/**
	 * 设置Node的点击回调
	 */
	public interface OnTreeNodeClickListener {
		void onClick(Node node, int position);
	}

	private OnTreeNodeClickListener onTreeNodeClickListener;

	public void setOnTreeNodeClickListener(
			OnTreeNodeClickListener onTreeNodeClickListener) {
		this.onTreeNodeClickListener = onTreeNodeClickListener;
	}

	/**
	 * 构造
	 * 
	 * @param tree
	 * @param context
	 * @param datas
	 * @param defaultExpandLevel
	 * @throws IllegalAccessException
	 */
	public TreeListViewAdapter(ListView tree, Context context, List<T> datas,
			int defaultExpandLevel) throws IllegalAccessException {
		this.context = context;
		inflater = LayoutInflater.from(context);
		allNodes = TreeHelper.sortNodes(datas, defaultExpandLevel);
		visibleNodes = TreeHelper.filterVisibleNodes(allNodes);
		this.tree = tree;

		this.tree.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {
				expandOrCollapse(i);
				if (onTreeNodeClickListener != null) {
					onTreeNodeClickListener.onClick(visibleNodes.get(i), i);
				}
			}
		});
	}

	private void expandOrCollapse(int position) {
		Node n = visibleNodes.get(position);
		if (n != null) {
			if (n.isLeaf()) {
				return;
			}
			n.setExpand(!n.isExpand());
			visibleNodes = TreeHelper.filterVisibleNodes(allNodes);
			notifyDataSetChanged();
		}
	}

	@Override
	public int getCount() {
		return visibleNodes.size();
	}

	@Override
	public Object getItem(int i) {
		return visibleNodes.get(i);
	}

	@Override
	public long getItemId(int i) {
		return i;
	}

	@Override
	public View getView(int i, View view, ViewGroup viewGroup) {
		Node node = visibleNodes.get(i);
		view = getConvertView(node, i, view, viewGroup);

		// 设置内边距
		view.setPadding(node.getLevel() * 30, 3, 3, 3);
		return view;
	}

	public abstract View getConvertView(Node node, int position,
			View convertView, ViewGroup viewGroup);
}
